const usernameInput = $('#username')[0];
const usernameError = $('#username-error')[0];
const usernameSuccess = $('#username-success')[0];

const emailInput = $('#email')[0];
const emailError = $('#email-error')[0];
const emailSuccess = $('#email-success')[0];

const submitButton = $('#submit')[0];
const resetButton = $('#reset')[0];

// 绑定事件
usernameInput.addEventListener('input', checkUsername1)
usernameInput.addEventListener('focusout', checkUsername2)

emailInput.addEventListener('input', checkEmail1)
emailInput.addEventListener('focusout', checkEmail2)

submitButton.addEventListener('click', submit)
resetButton.addEventListener('click', reset)


// 校验方法
function checkUsername1() {
    console.log('username变化', usernameInput.value)
    if (usernameInput.value.length < 6) {
        turnElem(usernameError, usernameSuccess)
        usernameInput.style.background = '#ffcccc';
        return false;
    }
    return true;
}

function checkUsername2() {
    if (checkUsername1()) {
        turnElem(usernameSuccess, usernameError)
        usernameInput.style.background = '#faffbd';
        console.log('username符合规范', usernameInput.value)
        return true;
    }
    return false;
}

function checkEmail1() {
    console.log('email变化', emailInput.value)
    if (isEmail(emailInput.value)) {
        turnElem(emailError, emailSuccess)
        emailInput.style.background = '#ffcccc';
        return false;
    }
    return true;

    function isEmail(str) {
        // 分析
        let atSymbol = 0;// @
        let dotSymbol = 0;// .
        for (let i = 1; i < str.length; i++)
            if (str.charAt(i) === '@') {
                atSymbol = i;// @的位置
                break;
            }
        for (let i = atSymbol + 1; i < str.length; i++)
            if (str.charAt(i) === '.')
                dotSymbol = i;// .的位置
        // 判定
        if (atSymbol === 0 || atSymbol === str.length - 2) return 1;// 域名
        if (dotSymbol === 0 || dotSymbol === str.length - 1) return 2;
        if (atSymbol < 5 || atSymbol > 20) return 3;// 用户名
        // 结果
        return 0;
    }
}

function checkEmail2() {
    if (checkEmail1()) {
        turnElem(emailSuccess, emailError)
        emailInput.style.background = '#faffbd';
        console.log('email符合规范', emailInput.value)
        return true;
    }
    return false;
}


function turnElem(showElem, hiddenElem, hiddenClass = 'display-none', showClass = 'tips') {
    showElem.classList.remove(hiddenClass)
    showElem.classList.add(showClass)
    hiddenElem.classList.remove(showClass)
    hiddenElem.classList.add(hiddenClass)
}


function submit() {
    let isUsername = checkUsername2();
    let isEmail = checkEmail2();
    if (isUsername && isEmail) {
        alert('注册成功，密码已发到你的邮箱，请查收。')
    }
}

function reset() {
    location.reload();
}
